<template>
  <div class="app-container">
    <div class="filter-container">

      <div class="custom-tree-container">
        <div class="block">
          <el-card class="box-card">
            <div
              slot="header"
              class="clearfix"
            >
              <span>省级</span>
              <el-button
                style="float: right; padding: 3px 0"
                type="text"
                @click.stop="handleCreate(1)"
              >添加
              </el-button>
            </div>
            <div
              v-for="(o,index) in dataCard1"
              :key="o.id"
              ref="level1"
              class="text item"
              @click="loadChild(o.areaLevel,o.areaCode,index,o.areaPath)"
            >
              {{ o.areaName + '--' + o.areaCode }}
              <el-button-group
                v-if="Btnshow1 === ('Btnshow1' + index)"
                style="float:right"
              >
                <el-button
                  icon="el-icon-edit"
                  size="mini"
                  @click.stop="handlerEdit(o)"
                />
                <el-button
                  icon="el-icon-delete"
                  size="mini"
                  @click.stop="handlerDel(o.id)"
                />
              </el-button-group>
            </div>
          </el-card>
        </div>
        <div class="block">
          <el-card class="box-card">
            <div
              slot="header"
              class="clearfix"
            >
              <span>市级</span>
              <el-button
                style="float: right; padding: 3px 0"
                type="text"
                @click.stop="handleCreate(2)"
              >添加
              </el-button>
            </div>
            <div
              v-for="(o,index) in dataCard2"
              :key="o.id"
              ref="level2"
              class="text item"
              @click="loadChild(o.areaLevel,o.areaCode,index,o.areaPath)"
            >
              {{ o.areaName + '--' + o.areaCode }}
              <el-button-group
                v-if="Btnshow2 === ('Btnshow2' + index)"
                style="float:right"
              >
                <el-button
                  icon="el-icon-edit"
                  size="mini"
                  @click.stop="handlerEdit(o)"
                />
                <el-button
                  icon="el-icon-delete"
                  size="mini"
                  @click.stop="handlerDel(o.id)"
                />
              </el-button-group>
            </div>
          </el-card>
        </div>
        <div class="block">
          <el-card class="box-card">
            <div
              slot="header"
              class="clearfix"
            >
              <span>区/县级</span>
              <el-button
                style="float: right; padding: 3px 0"
                type="text"
                @click.stop="handleCreate(3)"
              >添加
              </el-button>
            </div>
            <div
              v-for="(o,index) in dataCard3"
              :key="o.id"
              ref="level3"
              class="text item"
              @click="loadChild(o.areaLevel,o.areaCode,index,o.areaPath)"
            >
              {{ o.areaName + '--' + o.areaCode }}
              <el-button-group
                v-if="Btnshow3 === ('Btnshow3' + index)"
                style="float:right"
              >
                <el-button
                  icon="el-icon-edit"
                  size="mini"
                  @click.stop="handlerEdit(o)"
                />
                <el-button
                  icon="el-icon-delete"
                  size="mini"
                  @click.stop="handlerDel(o.id)"
                />
              </el-button-group>
            </div>
          </el-card>
        </div>
      </div>

    </div>

    <!-- 弹窗 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="closeOnClickModal"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="70px"
        style="width: 90%; margin-left:50px;"
      >
        <el-form-item
          label="名称"
          prop="areaName"
        >
          <el-input v-model="temp.areaName"/>
        </el-form-item>
        <el-form-item
          label="代码"
          prop="areaCode"
        >
          <el-input v-model="temp.areaCode"/>
        </el-form-item>
        <el-form-item
          label="父类"
          prop="parentCode"
          :disabled="true"
        >
          <el-input
            v-model="temp.parentCode"
            readonly="true"
          />
        </el-form-item>
        <el-form-item
          label="层级定位"
          prop="areaPath"
          :disabled="true"
        >
          <el-input
            v-model="temp.areaPath"
            readonly="true"
          />
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="saveData"
        >保存
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script type="text/ecmascript-6">
  import {cityAreaList, delCityArea, addCityArea,updateCityArea} from '@/api/cms/area'

  export default {
    components: {},
    data() {
      return {
        perms: [],
        tableData: [],
        dataLevel2: [],
        dataLevel3: [],
        dataCard1: [],
        dataCard2: [],
        dataCard3: [],
        Btnshow1: '',
        Btnshow2: '',
        Btnshow3: '',
        Btnshow4: '',
        levelPCode1: '0',
        levelPCode2: '',
        levelPCode3: '',
        levelPCode4: '',
        levelAPath1: '',
        levelAPath2: '',
        levelAPath3: '',
        levelAPath4: '',
        closeOnClickModal: false,
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '修改',
          create: '创建'
        },
        temp: {
          id: null,
          areaName: '',
          areaCode: '',
          areaLevel: '',
          zipCode: '',
          parentCode: '',
          areaPath: ''
        },
        rules: {
          areaName: [{required: true, message: '名称不能为空', trigger: 'change'}],
          areaCode: [{required: true, message: '行政区划代码不能为空', trigger: 'blur'}],
          zipCode: [{required: true, message: '邮编不能为空', trigger: 'change'}]
        }
      }
    },
    created() {
      this._getAreaList()
    },
    methods: {
      _getAreaList() {
        cityAreaList().then(res => {
          this.tableData = res.data
          this.dataCard1 = res.data.filter((item) => {
            return item.areaLevel === 1
          })
          this.dataLevel2 = res.data.filter((item) => {
            return item.areaLevel === 2
          })
          this.dataLevel3 = res.data.filter((item) => {
            return item.areaLevel === 3
          })
          this.loadChild(1, this.dataCard1[0].areaCode, 0, this.dataCard1[0].areaPath)
        })
      },
      loadChild(level, code, index, APath) {
        const _this = this
        switch (level) {
          case 1:
            this.dataCard2 = this.dataLevel2.filter((item) => {
              return item.parentCode === code
            })
            if (this.dataCard2.length > 0) {
              this.dataCard3 = this.dataLevel3.filter((item) => {
                return item.parentCode === this.dataCard2[0].areaCode
              })
            } else {
              this.dataCard3 = []
              this.levelPCode3 = ''
              this.levelPCode4 = ''
            }
            break
          case 2:
            this.dataCard3 = this.dataLevel3.filter((item) => {
              return item.parentCode === code
            })
            break
          case 3:
            break
        }
        this.$nextTick(() => {
          _this._changeActive(level, index, APath)
        })
      },
      _changeActive(level, index, APath) {
        const cnt = level
        for (let i = cnt; i <= 4; i++) {
          // 设置高亮
          const l = 'level' + i
          if (this.$refs[l]) {
            this.$refs[l].forEach((item) => {
              item.classList.remove('active')
            })
            if (i === cnt) {
              this.$refs[l][index].classList.add('active')
            } else {
              const dc = 'level' + (i - 1)
              if (this.$refs[l].length > 0 && this.$refs[dc].length > 0) {
                this.$refs[l][0].classList.add('active')
              }
            }
          }
          // 设置按钮显示
          const btn = 'Btnshow' + i
          if (i === cnt) {
            this[btn] = 'Btnshow' + i + index
          } else {
            this[btn] = 'Btnshow' + i + 0
          }
          // 设置PCode
          const lv = 'levelPCode' + i
          if (i > 1) {
            const dc = 'dataCard' + (i - 1)
            if (this[dc].length > 0) {
              if (i - 1 === cnt) {
                this[lv] = this[dc][index].areaCode
              } else {
                this[lv] = this[dc][0].areaCode
              }
            }
          }
          // 设置APath
          const lap = 'levelAPath' + i
          if (i > 1) {
            const dc = 'dataCard' + (i - 1)
            if (this[dc].length > 0) {
              if (i - 1 === cnt) {
                this[lap] = this[dc][index].areaPath
              } else {
                this[lap] = this[dc][0].areaPath
              }
            }
          }
        }
      },
      handlerEdit(item) {
        let _this = this;
        this.$confirm('您确定要修改该记录吗?', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          _this.copyTemp(item)
          _this.dialogStatus = 'update'
          _this.dialogFormVisible = true
          _this.$nextTick(() => {
            _this.$refs['dataForm'].clearValidate()
          })
        })
      },
      handlerDel(id) {
        let _this = this;
        this.$confirm('您确定要删除该记录吗?', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          delCityArea(id).then((res) => {
            _this.msgSuccess("删除成功");
            _this._getAreaList()
          })
        })
      },
      handleCreate(level) {
        const lv = 'levelPCode' + level
        const PCode = this[lv]
        console.log('pcode' + level + ':' + PCode)
        const lap = 'levelAPath' + level
        const APath = this[lap]
        console.log('path' + level + ':' + APath)
        if (level !== 1 && (PCode === '' || APath === '')) {
          this.$alert('请先选择上级', '提示信息', {
            confirmButtonText: '确定',
            callback: action => {
              this.$message({
                type: 'info',
                message: `请选择上级`
              })
            }
          })
        } else {
          this.resetTemp(level, PCode, APath)
          this.dialogStatus = 'create'
          this.dialogFormVisible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })
        }
      },
      resetTemp(level, PCode, APath) {
        this.temp = {
          id: null,
          areaName: '',
          areaCode: '',
          areaLevel: level,
          zipCode: '',
          parentCode: PCode,
          areaPath: APath

        }
      },
      copyTemp(item) {
        this.temp = {
          id: item.id,
          areaName: item.areaName,
          areaCode: item.areaCode,
          areaLevel: item.areaLevel,
          zipCode: item.zipCode,
          parentCode: item.parentCode,
          areaPath: item.areaPath

        }
      },
      saveData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if (this.temp.id != undefined) {
              updateCityArea(this.temp).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.dialogFormVisible = false;
                  this._getAreaList();
                } else {
                  this.msgError(response.msg);
                }
              });
            } else {
              addCityArea(this.temp).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.dialogFormVisible = false;
                  this._getAreaList();
                } else {
                  this.msgError(response.msg);
                }
              });
            }



          }
        })
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .custom-tree-container {
    display: flex;
    align-content: space-between;
  }

  .custom-tree-container .block {
    flex: 1;
    margin: 0 10px;
  }

  .box-card {
    width: 98%;
  }

  .text {
    font-size: 16px;
    line-height: 32px;
    height: 40px;
    padding: 4px;
  }

  .item {
    cursor: pointer;
    border-bottom: 1px dashed #f0f0f0;
    vertical-align: middle;
  }

  .item.active {
    background-color: #f0f0f0;
  }

  .item:hover {
    background-color: #f0f0f0;
  }

  .clearfix:after {
    clear: both;
  }
</style>
